import type { HomeType } from '../../interface'
import type { PickerProps } from 'antd-mobile/es/components/picker'
import type { Dictionary } from '@/api/base/interface'

import { useLayoutEffect } from 'react'
import { getOptions } from './config'
import { Plate, PlateSelector } from '../Plate'
import { useLocalObservable } from 'mobx-react'
import { asserts, rpxToPx } from '@/utils/share'
import { runInAction } from 'mobx'
import { Space } from 'antd-mobile'

import styles from './index.module.less'
import * as echarts from 'echarts'

interface Props {
    className?: string
    /** 数据 */
    data: HomeType.StudentDatum[]
    /** 培训班类别择器选项 */
    classCategoryOptions: Dictionary.Res

    onSelectCursorType: (v: string) => void
}

/** 学员统计 */
const StudentStatistics = (props: Props) => {
    const { data } = props

    const store = useLocalObservable(() => ({
        /** 当前课程类型 */
        currentCursorType: null as string | null,
    }))

    useLayoutEffect(() => {
        const chartDom = document.getElementById('studentStatistics')
        if (!chartDom) return

        const myChart = echarts.init(chartDom)

        const dataByOptions = data.reduce(
            (acc, cur) => {
                acc.month.push(`${cur.month}月`)
                acc.realTotal.push(cur.real_total)
                acc.qualifiedTotal.push(cur.qualified_total)
                return acc
            },
            {
                month: [] as string[],
                realTotal: [] as number[],
                qualifiedTotal: [] as number[],
            },
        )

        const options = getOptions(dataByOptions)
        myChart.setOption(options)
    }, [data])

    /** 选中课程类型 */
    const onSelectCursorType: PickerProps['onConfirm'] = ([v]) => {
        if (!asserts.isString(v)) return

        props.onSelectCursorType?.(v)

        runInAction(() => {
            store.currentCursorType = v
        })
    }

    const Title = (
        <>
            <div>学员统计（月）</div>
            <Space>
                {/* 班级类型 */}
                <PlateSelector
                    style={{ maxWidth: rpxToPx(300) }}
                    value={[store.currentCursorType]}
                    options={props.classCategoryOptions}
                    onConfirm={onSelectCursorType}
                />
            </Space>
        </>
    )

    return (
        <Plate
            className={`${styles.studentStatistics} ${props.className}`}
            title={Title}
            showEmpty={data.length === 0}
        >
            <div id="studentStatistics" style={{ height: rpxToPx(528, { base: 750 }) }} />
        </Plate>
    )
}

export default StudentStatistics
